package com.siblings.loan.ui.steps.view

import android.annotation.SuppressLint
import android.content.Intent
import android.view.View
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lib.base.utils.DensityUtils
import com.lib.base.utils.ImageUtil
import com.siblings.lib_baseadapter.SIBOnItemChildClickListener
import com.siblings.loan.R
import com.siblings.loan.app.Apps
import com.siblings.loan.databinding.ItemStepOcrBinding
import com.siblings.loan.http.ApiService
import com.siblings.loan.http.ApiService.addCommonParams
import com.siblings.loan.http.HttpHelper
import com.siblings.loan.ui.steps.act.SibCameraOcrAct
import com.siblings.loan.ui.steps.act.SibStepsAct
import com.siblings.loan.ui.steps.adapter.SibStepOcrTypeAdapter
import com.siblings.loan.utils.decoration.LinearSpacingItemDecoration
import com.siblings.loan.utils.dialog.PhotoDialog
import com.siblings.loan.utils.event.SibEventType
import org.json.JSONObject

/**
 * SiblingsLoan
 * @Author wwdeng
 * @CreateTime: 2024/7/10 15:13
 * @Annotation：步骤联系人样式
 */
@SuppressLint("NotifyDataSetChanged")
class SibStepOcrView(private val stepAct: SibStepsAct) {
    var binding = ItemStepOcrBinding.inflate(stepAct.layoutInflater)

    private val typeTitleList = arrayListOf(
        "${Apps.app.getString(R.string.step_ocr_idcard)},IDCARD",
        "${Apps.app.getString(R.string.step_ocr_drving_license)},DRIVING",
        "${Apps.app.getString(R.string.step_ocr_drving_passport)},PASSPORT"
    )
    private val typeImgNormalList = arrayListOf(
        R.mipmap.pic_step_ocr_idcard_normal,
        R.mipmap.pic_step_ocr_drving_license_normal,
        R.mipmap.pic_step_ocr_passport_normal
    )
    private val typeImgSelectList = arrayListOf(
        R.mipmap.pic_step_ocr_idcard_select,
        R.mipmap.pic_step_ocr_drving_license_select,
        R.mipmap.pic_step_ocr_passport_select
    )

    @SuppressLint("StaticFieldLeak")
    private var typeAdapter: SibStepOcrTypeAdapter? = null
    private var selectItem: JSONObject? = null
    private var photoDialog: PhotoDialog? = null

    //是否是正面
    private var isFront = true
    //正面照
    private var imgFrontUrl = ""
    //背面照
    private var imgBackUrl = ""

    init {
        //初始化Views
        initSibOcrViews()
        //初始化数据
        initSibOcrData()
        //初始化事件监听
        initSibOcrListener()
    }

    /**
     * Ocr样式
     */
    fun includeSibStepOcrView(): View {
        return binding.root
    }

    /**
     * 初始化View
     */
    private fun initSibOcrViews(){
//        binding.recyclerView.setHasFixedSize(true)
        binding.recyclerView.isNestedScrollingEnabled = false
        binding.recyclerView.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(stepAct)
        layoutManager.orientation = RecyclerView.VERTICAL
        binding.recyclerView.layoutManager = layoutManager
        val topDecoration = DensityUtils.dp2px(10f)
        binding.recyclerView.addItemDecoration(LinearSpacingItemDecoration(0,0,topDecoration,topDecoration))
        typeAdapter = SibStepOcrTypeAdapter(binding.recyclerView)
        binding.recyclerView.adapter = typeAdapter!!
        binding.recyclerView.itemAnimator = DefaultItemAnimator()
        typeAdapter!!.setOnItemChildClickListener(SIBOnItemChildClickListener { _, _, position ->
            val item = typeAdapter!!.getItem(position)
            if (item.optBoolean("isSelect",false)){
                return@SIBOnItemChildClickListener
            }
            selectItem = item
            for (i in 0..<typeAdapter!!.itemCount){
                val obj = typeAdapter!!.getItem(i)
                obj.put("isSelect",false)
                if (i == position){
                    obj.put("isSelect",true)
                }
            }
            typeAdapter!!.notifyDataSetChanged()

            //设置显示Ocr类型
            showSibOcrTypeViews()
        })
    }

    /**
     * 初始化数据
     */
    private fun initSibOcrData(){
        val typeList = arrayListOf<JSONObject>()
        for (i in 0..<typeTitleList.size){
            val item = JSONObject()
            item.put("ocrTitle",typeTitleList[i].split(",")[0])
            item.put("ocrType",typeTitleList[i].split(",")[1])
            item.put("imgSelect",typeImgSelectList[i])
            item.put("imgNormal",typeImgNormalList[i])
            if (i == 0){
                item.put("isSelect",true)
                selectItem = item
            } else {
                item.put("isSelect",false)
            }
            typeList.add(item)
        }
        typeAdapter!!.data = typeList
        //设置显示Ocr类型
        showSibOcrTypeViews()
    }

    /**
     * 初始化事件
     */
    private fun initSibOcrListener(){
        //idcard 正面
        binding.idcardLayout.frontLayout.setOnClickListener { onSibClickListener(it) }
        //idcard 反面
        binding.idcardLayout.backLayout.setOnClickListener { onSibClickListener(it) }
        //驾驶证 正面
        binding.drvingLicenseLayout.frontLayout.setOnClickListener { onSibClickListener(it) }
        //驾驶证 反面
        binding.drvingLicenseLayout.backLayout.setOnClickListener { onSibClickListener(it) }
        //护照 正面
        binding.passportLayout.passportLayout.setOnClickListener { onSibClickListener(it) }

        //提交
        binding.btnNext.setOnClickListener {
            if (selectItem == null){
                return@setOnClickListener
            }
            val ocrType = selectItem!!.optString("ocrType")
            if (!isSibAllowSubmit()){
                stepAct.showSibTipsDialog(ocrType)
                return@setOnClickListener
            }
            val params = JSONObject().addCommonParams().apply {
                put("path", ApiService.API_PATH.SIB_API_OCR_INFO_PATH)
                put("cardType",ocrType)//证件类型（PASSPORT、IDCARD、DRIVING、FACE）
            }
            params.put("cardImgUrl",imgFrontUrl)//证件图片正面
            if (imgBackUrl.isNotEmpty()){
                params.put("cardBackImgUrl",imgBackUrl)//证件图片反面
            }
            stepAct.mvpPresenter.onSibSubmitProcessAction(params)
            HttpHelper.addSibEventAction(String.format(SibEventType.CLICK.SIB_CLICK_STEP_OCR_XX_NEXT,ocrType),"")
        }
    }

    /**
     * 显示Ocr类型
     */
    private fun showSibOcrTypeViews(){
        if (selectItem == null){
            return
        }
        imgFrontUrl = ""
        imgBackUrl = ""
        binding.idcardLayout.idcardLayout.visibility = View.GONE
        binding.idcardLayout.imgFront.setImageResource(R.mipmap.pic_step_ocr_front)
        binding.idcardLayout.imgBack.setImageResource(R.mipmap.pic_step_ocr_back)
        binding.drvingLicenseLayout.drvingLicenseLayout.visibility = View.GONE
        binding.drvingLicenseLayout.imgFront.setImageResource(R.mipmap.pic_step_ocr_front)
        binding.drvingLicenseLayout.imgBack.setImageResource(R.mipmap.pic_step_ocr_back)
        binding.passportLayout.passportLayout.visibility = View.GONE
        binding.passportLayout.imgView.setImageResource(R.mipmap.pic_step_ocr_front)
        when(selectItem!!.optString("ocrType")){
            "DRIVING" -> {//驾驶证
                binding.drvingLicenseLayout.drvingLicenseLayout.visibility = View.VISIBLE
            }
            "PASSPORT" -> {//护照
                binding.passportLayout.passportLayout.visibility = View.VISIBLE
            }
            else -> {//身份证
                binding.idcardLayout.idcardLayout.visibility = View.VISIBLE
            }
        }
    }

    /**
     * 点击选择图片
     */
    private fun onSibClickListener(v: View){
        when(v.id){
            binding.idcardLayout.frontLayout.id -> {//身份证 正面
                isFront = true
                showSibPhotoDialog("IdCard Front")
            }
            binding.idcardLayout.backLayout.id -> {//身份证 反面
                isFront = false
                showSibPhotoDialog("IdCard Back")
            }
            binding.drvingLicenseLayout.frontLayout.id -> {//驾驶证 正面
                isFront = true
                showSibPhotoDialog("DriverLicense Front")
            }
            binding.drvingLicenseLayout.backLayout.id -> {//驾驶证 反面
                isFront = false
                showSibPhotoDialog("DriverLicense Back")
            }
            binding.passportLayout.passportLayout.id -> {//护照
                showSibPhotoDialog("Passport")
            }
        }
    }

    /**
     * 相机、相册
     */
    private fun showSibPhotoDialog(eventRemark: String){
        if (photoDialog == null){
            photoDialog = PhotoDialog(stepAct,eventRemark,object : PhotoDialog.IDialogCallback{
                override fun openCamera() {
                    HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_CAMERA,eventRemark)
                    openSibCamera()
                }
                override fun openAlbum() {
                    HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_ALBUM,eventRemark)
                    openSibAlbum()
                }
            })
        }
        photoDialog!!.show()
    }

    /**
     * 打开相册
     */
    private fun openSibAlbum(){
        stepAct.pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
    }

    /**
     * 打开相机
     */
    private fun openSibCamera(){
        if (selectItem != null){
            stepAct.takePhotoResultLauncher.launch(Intent(stepAct, SibCameraOcrAct::class.java))
        }
    }

    /**
     * 显示选择的图片
     */
    fun showSibSelectImags(imgPath: String,imgUrl: String){
        when(selectItem!!.optString("ocrType")){
            "DRIVING" -> {//驾驶证
                if (isFront){
                    imgFrontUrl = imgUrl
                    ImageUtil.instance!!.loadImageUrl(stepAct,binding.drvingLicenseLayout.imgFront,imgPath)
                } else {
                    imgBackUrl = imgUrl
                    ImageUtil.instance!!.loadImageUrl(stepAct,binding.drvingLicenseLayout.imgBack,imgPath)
                }
            }
            "PASSPORT" -> {//护照
                imgFrontUrl = imgUrl
                ImageUtil.instance!!.loadImageUrl(stepAct,binding.passportLayout.imgView,imgPath)
            }
            else -> {//身份证
                if (isFront){
                    imgFrontUrl = imgUrl
                    ImageUtil.instance!!.loadImageUrl(stepAct,binding.idcardLayout.imgFront,imgPath)
                } else {
                    imgBackUrl = imgUrl
                    ImageUtil.instance!!.loadImageUrl(stepAct,binding.idcardLayout.imgBack,imgPath)
                }
            }
        }
    }

    /**
     * 检查是否填写完整
     * 当且仅当 isMust=”NO“为非必填
     */
    private fun isSibAllowSubmit(): Boolean{
        if (imgFrontUrl.isEmpty()){
            return false
        }
        val ocrType = selectItem!!.optString("ocrType")
        if (imgBackUrl.isEmpty() && (ocrType == "DRIVING" || ocrType == "IDCARD")){
            return false
        }
        return true
    }

    fun onDestroy() {
        if (typeAdapter != null){
            typeAdapter = null
        }
        if (selectItem != null){
            selectItem = null
        }
        if (photoDialog != null){
            photoDialog = null
        }
        imgFrontUrl = ""
        imgBackUrl = ""
    }
}